package controllers;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import play.data.validation.Required;
import models.Dealer;
import models.Device;
import models.DeviceModel;
import models.Operator;
import models.Oplog;
import models.Region;
import models.Shop;
import models.ShopStatus;
import models.Standard;
import models.SystemParams;
import notifiers.MailUtils;
import services.AuthorityService;
import services.DealerService;
import services.DeviceModelService;
import services.DeviceService;
import services.HraStandardService;
import services.RegionService;
import services.ShopService;
import services.SystemParamService;
import utils.BizConstants;
import utils.ExcelUtil;
import utils.FileConfig;
import utils.Validate;
import vos.DealerVo;
import vos.DeviceSearchVo;
import vos.DeviceVo;
import vos.HraStandardSearchVo;
import vos.ReturnCode;
import vos.ReturnListVo;
import vos.ShopSearchVo;
import vos.ShopVo;

public class ShopController extends BaseController {
	/**
	 * 门店列表页面
	 *
	 * @Title: shopList 
	 * @return: void
	 */
	public static void shopList(String menuid){
		Operator oper=getLoginUser();
		List<String> auths=AuthorityService.getAuthorityByOperAndMenu(menuid,oper.operatorid);
		for(String auth : auths){
			renderArgs.put(auth, auth);
		}
		render();
	}
	/**
	 * 获取门店列表
	 *
	 * @Title: getShop 
	 * @return: void
	 */
	public static void getShop(int page,int rows, String sort,String order,
			String resperson,String shopid,String shopname,String dealerid,
			String dealername,Boolean isflag,String regionid){
		if(page==0){
			page=1;
		}
		if(rows==0){
			rows=BizConstants.pagesize;
		}
		ShopSearchVo vo =new ShopSearchVo(page,rows,order,sort,shopid,shopname,dealerid,dealername,resperson,isflag,regionid);
		long total=ShopService.countShop(vo);
		ReturnListVo listVo=new ReturnListVo();
		listVo.setTotal(total);
		List<Shop> lists=ShopService.listShop(vo);
		listVo.setRows(lists);
		renderJSON(listVo);
	}
	/**
	 * 批量启用
	 *
	 * @Title: betchEnable 
	 * @return: void
	 */
	public static void betchEnable(String ids){
		Operator oper=getLoginUser();
		if(StringUtils.isEmpty(ids)){
			renderFailedJson(ReturnCode.ErrorCode,"未选中记录");
		}
		String[] id=ids.split(",");
		List<String> listid=new ArrayList<String>();
		Collections.addAll(listid, id);
		for(String ss: listid){
			ShopVo shop=ShopService.getById(ss);
			if(shop==null){
				renderFailedJson(ReturnCode.ErrorCode,"门店不存在，门店编号为："+ss);
			}
			if(shop.dealerflag){
				renderFailedJson(ReturnCode.ErrorCode,"门店所属经销商被停用，门店编号为："+ss);
			}
		}
		boolean issuccess=ShopService.betchEnable(listid,oper.operatorid);
		if(issuccess){
			Oplog oplog=new Oplog(oper.operatorid,"批量启用门店"+ids,"门店管理");
			oplog.save(oplog);
			renderFailedJson(ReturnCode.SuccessCode,"启用成功");
		}
		else{
			renderFailedJson(ReturnCode.ErrorCode,"启用失败");
		}
	}
	/**
	 * 批量停用
	 *
	 * @Title: betchEnable 
	 * @return: void
	 */
	public static void betchDisable(String ids){
		Operator oper=getLoginUser();
		if(StringUtils.isEmpty(ids)){
			renderFailedJson(ReturnCode.ErrorCode,"未选中记录");
		}
		String[] id=ids.split(",");
		List<String> listid=new ArrayList<String>();
		Collections.addAll(listid, id);
		boolean issuccess=ShopService.betchDisable(listid,oper.operatorid);
		if(issuccess){
			Oplog oplog=new Oplog(oper.operatorid,"批量停用门店"+ids,"门店管理");
			oplog.save(oplog);
			renderFailedJson(ReturnCode.SuccessCode,"停用成功");
		}
		else{
			renderFailedJson(ReturnCode.ErrorCode,"停用失败");
		}
	}
	/**
	 * 批量删除
	 *
	 * @Title: betchEnable 
	 * @return: void
	 */
	public static void betchDel(String ids){
		if(StringUtils.isEmpty(ids)){
			renderFailedJson(ReturnCode.ErrorCode,"未选中记录");
		}
		String[] id=ids.split(",");
		List<String> listid=new ArrayList<String>();
		Collections.addAll(listid, id);
		List<String> devices = DeviceService.selectByShops(listid);
		if(devices!=null&&devices.size()>0){
			renderFailedJson(ReturnCode.ErrorCode,"门店下有设备存在");
		}
		boolean issuccess=ShopService.betchDel(listid);
		if(issuccess){
			Operator oper=getLoginUser();
			Oplog oplog=new Oplog(oper.operatorid,"批量删除门店"+ids,"门店管理");
			oplog.save(oplog);
			renderFailedJson(ReturnCode.SuccessCode,"删除成功");
		}
		else{
			renderFailedJson(ReturnCode.ErrorCode,"删除失败");
		}
	}
	/**
	 * 删除记录
	 *
	 * @Title: delShop 
	 * @param id 门店id
	 * @return: void
	 */
	public static void delShop(String id){
		if(StringUtils.isEmpty(id)){
			renderFailedJson(ReturnCode.ErrorCode,"选中记录不能为空");
		}
		List<Device> device=DeviceService.findByShop(id);
		if(device!=null&&device.size()>0){
			renderFailedJson(ReturnCode.ErrorCode,"门店下有设备存在");
		}
		boolean issuccess=ShopService.delShop(id);
		if(issuccess){
			Operator oper=getLoginUser();
			Oplog oplog=new Oplog(oper.operatorid,"删除门店"+id,"门店管理");
			oplog.save(oplog);
			renderFailedJson(ReturnCode.SuccessCode,"删除成功");
		}
		else{
			renderFailedJson(ReturnCode.ErrorCode,"删除失败");
		}
	}
	/**
	 * 添加门店
	 *
	 * @Title: addShop 
	 * @return: void
	 */
	public static void shopAdd(){
		render();
	}
	/**
	 * 复制门店
	 *
	 * @Title: addShop 
	 * @return: void
	 */
	public static void shopCopy(String id){
		ShopVo oldShop=ShopService.getById(id);
		renderArgs.put("shop", oldShop);
		render("ShopController/shopAdd.html");
	}
	/**
	 * 验证门店编号是否存在
	 *
	 * @Title: checkCode 
	 * @param shopid 门店id
	 * @return: void
	 */
	public static void checkCode(String value){
//		if(!Validate.isEnglishNum(value)){
//			renderFailedJson(ReturnCode.ErrorCode, "门店编号格式不正确");
//		}
		if(StringUtils.isEmpty(value)){
			renderFailedJson(ReturnCode.ErrorCode, "编号不能为空");
		}
		boolean isexist=ShopService.checkCode(value);
		if(isexist){
			renderFailedJson(ReturnCode.ErrorCode, "编号已存在");
		}
		else{
			renderFailedJson(ReturnCode.SuccessCode, "该编号可以使用");
		}
	}
	/**
	 * 保存门店信息
	 *
	 * @Title: saveShop 
	 * @param shop 门店对象
	 * @return: void
	 */
	public static void saveShop(Shop shop){
		if(!checkAuthority("SHOP_ADD")){
			renderFailedJson(ReturnCode.ErrorCode, "您没有操作权限，请联系管理员");
		}
		Operator oper=getLoginUser();
		if(shop==null){
			renderFailedJson(ReturnCode.ErrorCode, "门店不能为空");
		}
		if(StringUtils.isEmpty(shop.shopid)){
			renderFailedJson(ReturnCode.ErrorCode, "编号不能为空");
		}
		if(StringUtils.isEmpty(shop.dealerid)){
			renderFailedJson(ReturnCode.ErrorCode, "经销商不能为空");
		}
		DealerVo dealer=DealerService.getById(shop.dealerid);
		if(dealer==null){
			renderFailedJson(ReturnCode.ErrorCode, "经销商不存在");
		}
		if(shop.remark.length()>255){
			renderFailedJson(ReturnCode.ErrorCode, "备注长度不可大于255");
		}
		if(StringUtils.isEmpty(shop.regionid)){
			renderFailedJson(ReturnCode.ErrorCode, "地区不能为空");
		}
		if(shop.opendate==null){
			renderFailedJson(ReturnCode.ErrorCode, "开业时间不能为空");
		}
		Region region=RegionService.getById(shop.regionid);
		if(region==null){
			renderFailedJson(ReturnCode.ErrorCode, "地区不存在");
		}
		ShopVo oldShop=ShopService.getById(shop.shopid);
		if(oldShop!=null){
			renderFailedJson(ReturnCode.ErrorCode, "门店已存在");
		}
//		if(!Validate.isEnglishNum(shop.shopid)){
//			renderFailedJson(ReturnCode.ErrorCode, "门店编号格式不正确");
//		}
		//验证手机号
		if(!Validate.isMobile(shop.resmobile)){
			renderFailedJson(ReturnCode.ErrorCode, "手机格式不正确");
		}
		
		shop.createname=oper.operatorid;
		boolean isSuccess=ShopService.saveShop(shop);
		if(isSuccess){
			Oplog oplog=new Oplog(oper.operatorid,"创建门店"+shop.shopid,"门店管理");
			oplog.save(oplog);
			renderFailedJson(ReturnCode.SuccessCode, "保存成功");
		}
		else{
			renderFailedJson(ReturnCode.ErrorCode, "保存失败");
		}
	}
	/**
	 * 编辑门店
	 *
	 * @Title: shopEdit 
	 * @return: void
	 */
	public static void shopEdit(String id){
		ShopVo oldShop=ShopService.getVoById(id);
		renderArgs.put("shop", oldShop);
		render();
	}
	/**
	 * 保存门店信息
	 *
	 * @Title: saveShop 
	 * @param shop 门店对象
	 * @return: void
	 */
	public static void updateShop(Shop shop){
		if(!checkAuthority("SHOP_EDIT")){
			renderFailedJson(ReturnCode.ErrorCode, "您没有操作权限，请联系管理员");
		}
		Operator oper=getLoginUser();
		if(shop==null){
			renderFailedJson(ReturnCode.ErrorCode, "门店不能为空");
		}
		if(StringUtils.isEmpty(shop.dealerid)){
			renderFailedJson(ReturnCode.ErrorCode, "经销商不能为空");
		}
		DealerVo dealer=DealerService.getById(shop.dealerid);
		if(dealer==null){
			renderFailedJson(ReturnCode.ErrorCode, "经销商不存在");
		}
		if(StringUtils.isEmpty(shop.shopid)){
			renderFailedJson(ReturnCode.ErrorCode, "编号不能为空");
		}
		if(StringUtils.isEmpty(shop.regionid)){
			renderFailedJson(ReturnCode.ErrorCode, "地区不能为空");
		}
		Region region=RegionService.getById(shop.regionid);
		if(region==null){
			renderFailedJson(ReturnCode.ErrorCode, "地区不存在");
		}
		if(shop.remark.length()>255){
			renderFailedJson(ReturnCode.ErrorCode, "备注长度不可大于255");
		}
		if(shop.statusid==null){
			renderFailedJson(ReturnCode.ErrorCode, "门店状态不能为空");
		}
		ShopVo oldShop=ShopService.getById(shop.shopid);
		if(oldShop==null){
			renderFailedJson(ReturnCode.ErrorCode, "门店不存在");
		}
		
		shop.modifyname=oper.operatorid;
		boolean isSuccess=ShopService.updateShop(shop);
		if(isSuccess){
			if(oldShop.statusid!=shop.statusid){
				ShopVo newShop=ShopService.getById(shop.shopid);
				String emailparam=SystemParamService.getByCacheId(BizConstants.SHOPSTATUSCHANGE_EMAIL);
				if(emailparam!=null||StringUtils.isNotEmpty(emailparam)){
					MailUtils.ChangeShopStatus(newShop,emailparam);
				}
			}
			Oplog oplog=new Oplog(oper.operatorid,"修改门店"+shop.shopid,"门店管理");
			oplog.save(oplog);
			renderFailedJson(ReturnCode.SuccessCode, "保存成功");
		}
		else{
			renderFailedJson(ReturnCode.ErrorCode, "保存失败");
		}
	}
	/**
	 * 查看门店
	 *
	 * @Title: shopEdit 
	 * @return: void
	 */
	public static void shopView(String id){
		ShopVo Shop=ShopService.getViewById(id);
		renderArgs.put("shop", Shop);
		render();
	}
	/**
	 * 获取combobox内容
	 *
	 * @Title: getModel 
	 * @return: void
	 */
	public static void getCombobox(){
		List<Shop> shops=ShopService.getCombobox();
		List<Map<String,String>> combos=new ArrayList<Map<String,String>>();
		for(Shop shop : shops){
			Map<String,String> map=new HashMap<String,String>();
			map.put("id",shop.shopid);
			map.put("text", shop.shopname);
			combos.add(map);
		}
		renderJSON(combos);
	}
	/**
	 * 根据门店id获取设备
	 *
	 * @Title: getShop 
	 * @param dealerid
	 * @return: void
	 */
	public static void getDevice(int page,int rows, String sort,String order,String shopid){
		if(StringUtils.isEmpty(shopid)){
			renderJSON(null);
		}
		if(page==0){
			page=1;
		}
		if(rows==0){
			rows=BizConstants.pagesize;
		}
		DeviceSearchVo vo =new DeviceSearchVo(page,rows,order,sort,shopid);
		long total=DeviceService.countDeviceByShop(vo);
		ReturnListVo listVo=new ReturnListVo();
		List<DeviceVo> lists=DeviceService.getDeviceByShop(vo);
		listVo.setTotal(total);
		listVo.setRows(lists);
		renderJSON(listVo);
	}
	/**
	 * 导出为excel
	 *
	 * @Title: exportXls 
	 * @param resperson 联系人
	 * @param shopid 门店编号
	 * @param shopname门店名称
	 * @param dealerid 经销商编号
	 * @param dealername 经销商名称
	 * @param isflag 是否停用
	 * @return: void
	 */
	public static void exportXls(String shopid, String shopname, String dealerid,
			String dealername, String resperson,String regionid,
			Boolean isflag){
		if(!checkAuthority("SHOP_EXPORT")){
			renderFailedJson(ReturnCode.ErrorCode, "您没有操作权限，请联系管理员");
		}
		ShopSearchVo vo=new ShopSearchVo(shopid,shopname,dealerid,dealername,resperson,isflag,regionid);
		List<ShopVo> lists=ShopService.exportXls(vo);
		long y=System.currentTimeMillis();
		String fileName = "门店信息"+y+".csv";
        response.contentType = "application/x-download";
        Operator oper =getLoginUser();
        Oplog oplog=new Oplog(oper.operatorid,"导出门店信息","门店管理");
		oplog.save(oplog);
        renderBinary(ExcelUtil.buildExportFile(FileConfig.shopXlsTemplate, lists), fileName);
	}
	/**
	 * 获取状态下拉列表
	 *
	 * @Title: getStatusCombobox 
	 * @return: void
	 */
	public static void getStatusCombobox(){
		List<ShopStatus> status=ShopService.getStatusCombobox();
		List<Map<String,String>> combos=new ArrayList<Map<String,String>>();
		for(ShopStatus sta : status){
			Map<String,String> map=new HashMap<String,String>();
			map.put("id", Long.toString(sta.statusid));
			map.put("text", sta.statusname);
			combos.add(map);
		}
		renderJSON(combos);
	}
}
